import tkinter as tk
from tkinter import scrolledtext, messagebox
import requests

class ChatApp:
    def __init__(self, root):
        self.root = root
        self.root.title("API Chatbot")

        # 配置输入框
        tk.Label(root, text="API Key:").grid(row=0, column=0, sticky="w")
        self.api_key_entry = tk.Entry(root, width=50, show="*")
        self.api_key_entry.grid(row=0, column=1, padx=5, pady=5)

        tk.Label(root, text="Workspace:").grid(row=1, column=0, sticky="w")
        self.workspace_entry = tk.Entry(root, width=50)
        self.workspace_entry.grid(row=1, column=1, padx=5, pady=5)

        # 对话显示区域
        self.chat_display = scrolledtext.ScrolledText(root, width=60, height=20, state="disabled")
        self.chat_display.grid(row=2, column=0, columnspan=2, padx=5, pady=5)

        # 问题输入框
        self.question_entry = tk.Entry(root, width=50)
        self.question_entry.grid(row=3, column=0, padx=5, pady=5)

        # 发送按钮
        self.send_button = tk.Button(root, text="发送", command=self.send_message)
        self.send_button.grid(row=3, column=1, padx=5, pady=5)

    def send_message(self):
        """发送请求到 API 并显示响应"""
        question = self.question_entry.get()
        api_key = self.api_key_entry.get()
        workspace_name = self.workspace_entry.get()

        if not (question and api_key and workspace_name):
            messagebox.showerror("错误", "请填写 API Key、Workspace 和问题")
            return

        self.append_chat(f"你: {question}")

        answer, sources = self.ask_anythingllm(question, workspace_name, api_key)
        self.append_chat(f"AI: {answer}")
        
        if sources:
            source_titles = "\n".join([src['title'] for src in sources])
            self.append_chat(f"来源:\n{source_titles}")

        self.question_entry.delete(0, tk.END)  # 清空输入框

    def ask_anythingllm(self, question, workspace_name, api_key):
        """调用 API 获取回答"""
        # 替换为实际的 API 端点
        url = f"http://localhost:3001/api/v1/workspace/{workspace_name}/chat"

        # 身份验证，设置请求头
        headers = {
            "accept": "application/json",
            "Authorization": f"Bearer {api_key}",  #注意，替换apikey一定要保留Bearer 
            "Content-Type": "application/json"
        }
        data = {"message": question, "mode": "query"}

        try:
            response = requests.post(url, headers=headers, json=data)
            if response.status_code == 200:
                result = response.json()
                answer = result['textResponse'].split('</think>')[-1].strip()
                sources = result.get('sources', [])
                return answer, sources
            else:
                return f"Error: {response.text}", []
        except requests.exceptions.RequestException as e:
            return f"请求失败: {str(e)}", []

    def append_chat(self, text):
        """在聊天框中追加文本"""
        self.chat_display.config(state="normal")
        self.chat_display.insert(tk.END, text + "\n")
        self.chat_display.config(state="disabled")
        self.chat_display.yview(tk.END)

if __name__ == "__main__":
    root = tk.Tk()
    app = ChatApp(root)
    root.mainloop()